package client.test.ihm;

import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
import java.rmi.ConnectException;
import java.rmi.RemoteException;

import javax.swing.JOptionPane;
import javax.swing.JTextField;

import serveurChatRMI.rmi.interfaces.InterfaceSujetDiscussion;
import client.test.ImplAffichageClient;
import clientInterfaces.InterfaceAffichageClient;

public class SendAction implements ActionListener, KeyListener {

	JTextField text;
	InterfaceAffichageClient iac;
	InterfaceSujetDiscussion sd;
	IHMChatClient ihmChatClient;
	
	public SendAction(IHMChatClient ihmChatClient, JTextField textField, ImplAffichageClient iac, InterfaceSujetDiscussion sd) {
		this.text=textField;
		this.iac=iac;
		this.sd=sd;
		this.ihmChatClient=ihmChatClient;
	}

	public void send() {
		try {
			if(!text.getText().equals("")) {
			sd.diffuse(text.getText(), iac);
			text.setText("");
			}
		} catch (RemoteException e) {
			
		
			try {
				
				sd.inscription(iac);
				sd.diffuse(text.getText(), iac);
				text.setText("");
				
				
				} catch (ConnectException e1) {
					JOptionPane.showMessageDialog(ihmChatClient.getFenetre(), "Impossible de se connecter au serveur :\nProbleme de connexion", "Erreur", JOptionPane.WARNING_MESSAGE);
					e1.printStackTrace();
				} catch (RemoteException e1) {
					JOptionPane.showMessageDialog(ihmChatClient.getFenetre(), "Impossible de se connecter au serveur :\nProbleme de connexion au serveur", "Erreur", JOptionPane.WARNING_MESSAGE);
					e1.printStackTrace();
				} 

		}

	}
	
	@Override
	public void actionPerformed(ActionEvent arg0) {
		send();
	}

	@Override
	public void keyPressed(KeyEvent arg0) {
		if(arg0.getKeyCode()==KeyEvent.VK_ENTER) {
			send();
		}
		
	}

	@Override
	public void keyReleased(KeyEvent arg0) {
		// TODO Auto-generated method stub
		
	}

	@Override
	public void keyTyped(KeyEvent arg0) {
		// TODO Auto-generated method stub
		
	}
	
	

	
	
	
	

}
